package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.BuildConfig;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.GetTestCode;
import com.longqinuo.mycarservice.utils.MyTextWatcher;
import com.longqinuo.mycarservice.utils.PathUtils;


import org.json.JSONException;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link JustRegisterFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class JustRegisterFragment extends Fragment implements View.OnClickListener {
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;

    private String mPhoneNumber;
    private String mTestCode;
    private String mPassword;
    private RequestQueue queue;
    private FragmentManager manager;
    private FragmentTransaction mTransaction;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String url;
    private OnFragmentInteractionListener mListener;
    private EditText et_phone_number_register;
    private EditText et_test_code_register;
    private Button btn_get_code_register;
    private EditText et_pass_word_register;
    private ImageView iv_close_eye_register;
    private ImageView iv_open_eye_register;
    private Button btn_register;
    private static boolean isCodeRight = false;
    private static final int mWhat = 1;
    public JustRegisterFragment() {
        // Required empty public constructor
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case mWhat:
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    Log.e(">>>>>>", "event=" + event);
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        // 短信注册成功后，返回MainActivity,然后提示新好友
                        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                            Toast.makeText(getActivity(), "提交验证码成功",
                                    Toast.LENGTH_SHORT).show();
                            isCodeRight = true;

                        } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                            Toast.makeText(getActivity(), "验证码已经发送",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            ((Throwable) data).printStackTrace();
                        }
                    }
                    break;
            }

        }
    };


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment JustRegisterFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static JustRegisterFragment newInstance(String param1, String param2) {
        JustRegisterFragment fragment = new JustRegisterFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
        SMSSDK.initSDK(getActivity(), PathUtils.SMSSDK_KEY, PathUtils.SMSSDK_SECRET);//初始化验证码系统
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_just_register, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);

        mBack.setOnClickListener(this);
        mTitle.setText("立即注册");
        mEdit.setVisibility(View.INVISIBLE);
        et_phone_number_register = (EditText) view.findViewById(R.id.et_phone_number_register);
        et_test_code_register = (EditText) view.findViewById(R.id.et_test_code_register);
        btn_get_code_register = (Button) view.findViewById(R.id.btn_get_code_register);
        btn_get_code_register.setOnClickListener(this);
        et_pass_word_register = (EditText) view.findViewById(R.id.et_pass_word_register);
        iv_close_eye_register = (ImageView) view.findViewById(R.id.iv_close_eye_register);
        iv_close_eye_register.setOnClickListener(this);
        iv_open_eye_register = (ImageView) view.findViewById(R.id.iv_open_eye_register);
        iv_open_eye_register.setOnClickListener(this);
        btn_register = (Button) view.findViewById(R.id.btn_register);
        btn_register.setOnClickListener(this);

        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = handler.obtainMessage();
                msg.what = mWhat;
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);


    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        SMSSDK.unregisterAllEventHandler();
    }

    public boolean verificationPhoneNumber(String num) {
        if (VerificationUtils.matcherPhoneNum(num)) {
            return true;
        } else {
            Toast.makeText(getActivity(), "输入的手机号格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_code_register:
                mPhoneNumber = et_phone_number_register.getText().toString().trim();
                if (BuildConfig.DEBUG) Log.d(">>>>>>>>>", "点击了获取验证码按钮");
                if (verificationPhoneNumber(mPhoneNumber)) {
                    SMSSDK.getVerificationCode("86", mPhoneNumber);//获取验证码
                    et_test_code_register.addTextChangedListener(new MyTextWatcher(et_test_code_register,mPhoneNumber));

                    GetTestCode.waitNextClick(btn_get_code_register);

                }
                break;
            case R.id.btn_register:
                if (BuildConfig.DEBUG) Log.d(">>>>>>", "点击了注册按钮");

                if (submit()) {
                    if (isCodeRight) {
                        url = PathUtils.REGISTER_URL + "?phone=" + mPhoneNumber + "&password=" + mPassword;
                        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                if (BuildConfig.DEBUG) Log.d(">>>onResponse", jsonObject.toString());
                                try {
                                    requestRegister(jsonObject);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                            }
                        });
                        queue.add(request);
                    } else {
                        Toast.makeText(getActivity(), "输入验证码不正确", Toast.LENGTH_SHORT).show();
                    }

                }
                break;
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
        }
    }
    public void requestRegister(JSONObject jsonObject) throws JSONException {  //执行注册请求  的判断处理
        int code = jsonObject.getInt("code");
        switch (code) {
            case 0:
                Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
                mTransaction = manager.beginTransaction();
                JustRegisterFragment fragment = (JustRegisterFragment) manager.findFragmentByTag("JustRegister");
                mTransaction.detach(fragment);
                mTransaction.replace(R.id.ll_main_layout, LoginFragment.newInstance(mPhoneNumber, mPassword), "Login");
                mTransaction.addToBackStack("Login");
                mTransaction.commit();
                break;
            case -1:
                String error = jsonObject.getString("errorMessage");
                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
                break;

        }

    }

    private boolean submit() {
        // validate
        mPhoneNumber = et_phone_number_register.getText().toString().trim();
        if (TextUtils.isEmpty(mPhoneNumber)) {
            Toast.makeText(getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return false;
        }

        mTestCode = et_test_code_register.getText().toString().trim();
        if (TextUtils.isEmpty(mTestCode)) {
            Toast.makeText(getContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
            return false;
        }

        mPassword = et_pass_word_register.getText().toString().trim();
        if (TextUtils.isEmpty(mPassword)) {
            Toast.makeText(getContext(), "请输入密码", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;


    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
